package com.wfit.bankproject.config;



import com.wfit.bankproject.service.JwtService;
import com.wfit.bankproject.service.LoginUser;
import com.wfit.bankproject.service.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtSecurityFilter extends OncePerRequestFilter {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getServletPath().contains("/dologin")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取请求头中的token
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
       String jwt = authHeader.replace("Bearer ", "");;
       String userId = jwtService.extractUsername(jwt);

       LoginUser loginUser = redisCache.getCacheObject(userId);
//        System.out.println(loginUser);
        if (loginUser != null) {
//            List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(loginUser.getPermission());
            // 存入 SecurityContextHolder   参数一：用户信息   参数二：  参数三：权限认证
                UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(loginUser, null,loginUser.getAuthorities());
            //authToken.setDetails( new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
        }
        filterChain.doFilter(request, response);
    }
}
